
namespace NUtils
{
    public partial class Math
    {
        public static bool DoesIntersect(Segment segment, Sphere sphere)
        {
            Vector p1 = segment.Start;
            Vector p2 = segment.End;
            Vector p3 = sphere.Center;
            double r  = sphere.Radius;

            double a = Square(p2.X - p1.X) + Square(p2.Y - p1.Y) + Square(p2.Z - p1.Z);
            double b = 2.0 * ((p2.X - p1.X) * (p1.X - p3.X) 
                           +  (p2.Y - p1.Y) * (p1.Y - p3.Y)
                           +  (p2.Z - p1.Z) * (p1.Z - p3.Z));
            double c = Square(p3.X) + Square(p3.Y) + Square(p1.X) + 
                       Square(p1.Y) + Square(p3.Z) + Square(p1.Z);
            double d = 2.0 * (p3.X * p1.X + p3.Y * p1.Y + p3.Z * p1.Z);
            double i = (b * b) - (4 * a * (c - d - Square(r)));

            return i > -float.Epsilon;
        }
    }
}